package org.bdware.doip.endpoint.doipClient;

import com.google.gson.Gson;
import org.bdware.doip.core.doipMessage.DoipMessage;
import org.bdware.doip.core.doipMessage.DoipMessageFactory;
import org.bdware.doip.core.model.operations.BasicOperations;

import java.util.HashMap;
import java.util.Random;

public class StreamClientImpl extends DoipClientImpl{

    Random random = new Random();
    HashMap<Integer,DoipMessage> streamInProcess = new HashMap<>();

    public int retrieveByStream(String id,String element, DoipMessageCallback cb){
        DoipMessage msg =
                new DoipMessageFactory.DoipMessageBuilder()
                        .createRequest(id, BasicOperations.Retrieve.getName())
                        .create();
        if(element != null) msg.header.parameters.addAttribute("element", element);
        msg.header.parameters.addAttribute("action", "start");
        int requestID = random.nextInt();
        while(streamInProcess.containsKey(requestID)){
            requestID = random.nextInt();
        }
        msg.requestID = requestID;
        streamInProcess.put(requestID,msg);
        sendMessage(msg, cb);
        return msg.requestID;
    }

    public void stopAStream(int requestID, DoipMessageCallback cb){
        DoipMessage msg = streamInProcess.get(requestID);
        if(msg == null) return;
        msg.header.parameters.addAttribute("action", "stop");
        logger.debug("stop message: " + new Gson().toJson(msg.header.parameters.attributes));
        sendMessage(msg,cb);
    }

}
